import requests
from urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
from django.core.exceptions import SuspiciousOperation
import json


def download_image(url, timeout=10, max_retries=3):
    """安全下载图片内容
    Args:
        url: 图片URL
        timeout: 超时时间(秒)
        max_retries: 最大重试次数
    Returns:
        bytes: 图片二进制内容
    Raises:
        SuspiciousOperation: 如果URL不合法或下载失败
    """
    # 验证URL格式
    if not url.startswith(('http://', 'https://')):
        raise SuspiciousOperation(f"Invalid URL scheme: {url}")

    # 配置重试策略
    session = requests.Session()
    retries = Retry(
        total=max_retries,
        backoff_factor=0.5,
        status_forcelist=[500, 502, 503, 504]
    )
    session.mount('https://', HTTPAdapter(max_retries=retries))
    session.mount('http://', HTTPAdapter(max_retries=retries))

    try:
        response = session.get(url, timeout=timeout)
        response.raise_for_status()

        # 验证内容类型是图片
        content_type = response.headers.get('Content-Type', '')
        if not content_type.startswith('image/'):
            raise SuspiciousOperation(f"URL does not point to an image: {content_type}")

        return response.content
    except Exception as e:
        raise SuspiciousOperation(f"Failed to download image: {str(e)}")


def handle_front_result(front_result, task_data, r):
    print('front_result:', front_result)
    if not front_result or 'words_result' not in front_result:
        print('OCR识别失败，返回内容：', front_result)
        # 可以将任务标记为失败，写入结果，避免无限重试
        result_key = f"realname:result:{task_data['user_id']}"
        r.setex(result_key, 86400, json.dumps({
            'status': 'failed',
            'error': front_result.get('error_msg', 'unknown error'),
            'verified': False,
            'verified_at': None
        }))
        return